package net.jjjshop.common.service.lbt.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.jjjshop.common.cache.RedisUtil;
import net.jjjshop.common.entity.lbt.LbLineUp;
import net.jjjshop.common.entity.lbt.LbLotteryManager;
import net.jjjshop.common.entity.lbt.LbLotteryOrder;
import net.jjjshop.common.entity.lbt.LbSysConfigEntity;
import net.jjjshop.common.mapper.lbt.LbLineUpMapper;
import net.jjjshop.common.mapper.lbt.LbLotteryOrderMapper;
import net.jjjshop.common.service.lbt.LbLineUpService;
import net.jjjshop.common.service.lbt.LbLotteryManagerService;
import net.jjjshop.common.service.lbt.LbLotteryOrderService;
import net.jjjshop.common.service.lbt.LbSysConfigService;
import net.jjjshop.common.service.user.UserService;
import net.jjjshop.framework.common.exception.BusinessException;
import net.jjjshop.framework.util.LoginUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;


/**
 * 第三个模块抽奖池
 */

@Service("LbLotteryOrderService")
public class LbLotteryOrderServiceImpl extends ServiceImpl<LbLotteryOrderMapper, LbLotteryOrder> implements LbLotteryOrderService {

    @Autowired
    private LbLotteryOrderMapper dao;
    @Autowired
    private UserService userService;
    @Autowired
    private LbSysConfigService sysConfigService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private LbLotteryManagerService lotteryManagerService;
    private static final Logger logger = LoggerFactory.getLogger(LbLotteryOrderServiceImpl.class);

    @Override
    public List<LbLotteryManager> getLotteryRecord() {
        return dao.getLotteryRecord();
    }

    @Override
    public List<LbLotteryOrder> getLotteryList() {
        LbSysConfigEntity lbSysConfigEntity = sysConfigService.selectSysConfig();
        return dao.getLotteryList(lbSysConfigEntity.getLotteryNum());
    }

    @Override
    public Map<String, Object> getLotteryData() {
        LbSysConfigEntity lbSysConfigEntity = sysConfigService.selectSysConfig();
        LbLotteryManager lotteryInfo = dao.getLotteryInfo();
        Map<String,Object> map = new HashMap<>();
        if (null != lotteryInfo){
            String[] time = lbSysConfigEntity.getLotteryTime().split(",");
            Integer a=  dao.getLotteryNum();
            Integer b = a-lotteryInfo.getOrderNum();
            map.put("all",lotteryInfo.getOrderNum());
            map.put("cz",b);
            map.put("title",lotteryInfo.getName());
            map.put("hour",time[0]);
            map.put("min",time[1]);
            map.put("title",lotteryInfo.getName());
            if (b>=0){
                map.put("lotteryOrder",dao.getLotteryList2(lotteryInfo.getOrderNum()));
            }
        }

        return map;
    }

    @Override
    public LbLotteryManager  getQueryLottery()  {
        synchronized (this) {
            logger.info("抽奖开始处理中....");
            LbLotteryManager lotteryInfo = dao.getLotteryInfo();
            if (null == lotteryInfo){
                logger.info("未到抽奖....");
                throw new BusinessException("未到抽奖");
            }
            Integer a=  dao.getLotteryNum();
            Integer b = a-lotteryInfo.getOrderNum();
            if (b <0){
                logger.info("还未到达抽奖....");
                throw new BusinessException("未到抽奖");
            }
          Integer uid =  LoginUtil.getLoginUserRedisVo().getUserId();
            Object orderNo = redisUtil.get("LotteryOrderNo");
            if (null != orderNo) {
                LbLotteryManager lotteryRecord2 = dao.getLotteryRecord2(orderNo.toString());
                if (uid.intValue() == lotteryRecord2.getUid().intValue()){
                    lotteryRecord2.setOneself(1);
                }
                logger.info("已经抽过奖了....");
                return lotteryRecord2;
            }
            Object lotteryOrder = redisUtil.get("LotteryOrder");
            List<LbLotteryOrder> lotteryList = null;

            if (null == lotteryOrder) {

                lotteryList = dao.getLotteryList(lotteryInfo.getOrderNum());
                if (null != lotteryList && lotteryList.size() >= lotteryInfo.getOrderNum()) {
                    redisUtil.set("LotteryOrder", lotteryList);

                } else {
                    return null;
                }

            } else {
                lotteryList = (List<LbLotteryOrder>) lotteryOrder;
            }
            if (null != lotteryList && lotteryList.size() >= lotteryInfo.getOrderNum()) {
                int randomIndex = ThreadLocalRandom.current().nextInt(lotteryList.size());
                for (int i = 0; i < lotteryList.size(); i++) {
                    lotteryList.get(i).setTime(new Date());
                    if (i == randomIndex) {
                        lotteryList.get(i).setStatus(1);
                        redisUtil.set("LotteryOrderNo", lotteryList.get(i).getOrderNo(), 3600L);

                    } else {
                        lotteryList.get(i).setStatus(2);
                    }

                }
                updateBatchById(lotteryList);
                lotteryInfo.setOrderNo(lotteryList.get(randomIndex).getOrderNo());
                lotteryInfo.setStatus(1);
                lotteryInfo.setTime(new Date());
                lotteryInfo.setUid(lotteryList.get(randomIndex).getUid());
                lotteryManagerService.updateById(lotteryInfo);
                redisUtil.delete("LotteryOrder");
               LbLotteryManager lot= dao.getLotteryRecord2(lotteryInfo.getOrderNo());
                if (uid.intValue() == lot.getUid().intValue()){
                    lot.setOneself(1);
                }
                logger.info("抽奖成功....");
                return lot;
            }


        }
        return null;
    }


    @Override
    public LbLotteryManager  getQueryLottery2()  {
        synchronized (this) {
            logger.info("抽奖开始处理中....");
            LbLotteryManager lotteryInfo = dao.getLotteryInfo();
            if (null == lotteryInfo){
                logger.info("未到抽奖....");
                throw new BusinessException("未到抽奖");
            }
            Integer a=  dao.getLotteryNum();
            Integer b = a-lotteryInfo.getOrderNum();
            if (b <0){
                logger.info("还未到达抽奖....");
                throw new BusinessException("未到抽奖");
            }
            Object orderNo = redisUtil.get("LotteryOrderNo");
            if (null != orderNo) {
                LbLotteryManager lotteryRecord2 = dao.getLotteryRecord2(orderNo.toString());
                logger.info("已经抽过奖了....");
                return lotteryRecord2;
            }
            Object lotteryOrder = redisUtil.get("LotteryOrder");
            List<LbLotteryOrder> lotteryList = null;

            if (null == lotteryOrder) {

                lotteryList = dao.getLotteryList(lotteryInfo.getOrderNum());
                if (null != lotteryList && lotteryList.size() >= lotteryInfo.getOrderNum()) {
                    redisUtil.set("LotteryOrder", lotteryList);

                } else {
                    return null;
                }

            } else {
                lotteryList = (List<LbLotteryOrder>) lotteryOrder;
            }
            if (null != lotteryList && lotteryList.size() >= lotteryInfo.getOrderNum()) {
                int randomIndex = ThreadLocalRandom.current().nextInt(lotteryList.size());
                for (int i = 0; i < lotteryList.size(); i++) {
                    lotteryList.get(i).setTime(new Date());
                    if (i == randomIndex) {
                        lotteryList.get(i).setStatus(1);
                        redisUtil.set("LotteryOrderNo", lotteryList.get(i).getOrderNo(), 3600L);

                    } else {
                        lotteryList.get(i).setStatus(2);
                    }

                }
                updateBatchById(lotteryList);
                lotteryInfo.setOrderNo(lotteryList.get(randomIndex).getOrderNo());
                lotteryInfo.setStatus(1);
                lotteryInfo.setTime(new Date());
                lotteryInfo.setUid(lotteryList.get(randomIndex).getUid());
                lotteryManagerService.updateById(lotteryInfo);
                redisUtil.delete("LotteryOrder");
                LbLotteryManager lot= dao.getLotteryRecord2(lotteryInfo.getOrderNo());
                logger.info("抽奖成功....");
                return lot;
            }


        }
        return null;
    }

    @Override
    public LbLotteryManager queryResult() {
        Integer uid =  LoginUtil.getLoginUserRedisVo().getUserId();
        Object orderNo = redisUtil.get("LotteryOrderNo");
        if (null != orderNo) {
            LbLotteryManager lotteryRecord2 = dao.getLotteryRecord2(orderNo.toString());
            if (uid.intValue() == lotteryRecord2.getUid().intValue()){
                lotteryRecord2.setOneself(1);
            }
            return lotteryRecord2;
        }
        return null;
    }


}
